local HX = require "packages/lingling_extra/hxfs"




local role_getlogic = function()
  local role_logic = GameLogic:subclass("ling__role_logic")

  function role_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord" },
      { "lord", "rebel" },
      { "lord", "rebel", "renegade" },
      { "lord", "loyalist", "rebel", "renegade" },
      { "lord", "loyalist", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "renegade" },
      { "lord", "loyalist", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "renegade", "renegade" },
    }
  end

  function role_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)

    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
    end

    local function getPlayerByScreenName(Room, name)
      return table.find(Room.players, function(p)
        return p._splayer:getScreenName() == name
      end)
    end

    local croom = room.room
    local cowner = croom:getOwner()
    local owner = getPlayerByScreenName(room, cowner:getScreenName())
    if #table.filter(room.players, function(p) return p.id > 0 end) == 1 then  --只有一名玩家时可以自选身份
      local allrole = {}
      local oldrole = owner.role
      for _, r in ipairs(roles) do
        table.insertIfNeed(allrole, r)
      end
      table.insert(allrole, "Cancel")
      local truerole = room:askToChoice(owner, {
        choices = allrole,
        skill_name = "game_rule",
        prompt = "#ling__choose_role",
        cancelable = true,
      })
      if truerole and truerole ~= "Cancel" then
        owner.role = truerole
        for _, p in ipairs(room.players) do
          if p.role == owner.role and p.id ~= owner.id then
            p.role = oldrole
            break
          end
        end
      end
    end

    for i = 1, n do
      local p = room.players[i]
      if p.role == "lord" then
        room:setPlayerProperty(p, "role_shown", true)
      end
      room:broadcastProperty(p, "role")
    end
  end
  


    --- 公布武将
    function role_logic:broadcastGeneral()
      local room = self.room
      local players = room.players
      local realplayers = table.filter(players, function(p) return p.id > 0 end)
      local ifkill = true
  
      for _, p in ipairs(players) do
        assert(p.general ~= "")
  
        local general = Fk.generals[p.general]
        local deputy = Fk.generals[p.deputyGeneral]
        p.maxHp = p:getGeneralMaxHp()
        p.hp = deputy and math.floor((deputy.hp + general.hp) / 2) or general.hp
        p.shield = math.min(general.shield + (deputy and deputy.shield or 0), 5)
        -- TODO: setup AI here
  
        local changer = Fk.game_modes[room:getSettings('gameMode')]:getAdjustedProperty(p)
        if changer then
          for key, value in pairs(changer) do
            p[key] = value
          end
        end
        local fixMaxHp = Fk.generals[p.general].fixMaxHp
        local deputyFix = Fk.generals[p.deputyGeneral] and Fk.generals[p.deputyGeneral].fixMaxHp
        if deputyFix then
          fixMaxHp = fixMaxHp and math.min(fixMaxHp, deputyFix) or deputyFix
        end
        if fixMaxHp then
          p.maxHp = fixMaxHp
        end
        p.hp = math.min(p.maxHp, p.hp)
  
        if p.seat >= (room:getSettings("late_position_start") or 99) then
          local n = room:getSettings("late_position_extrasheild") or 0
          p.shield = p.shield + n
        
        end
        if p.role == "lord" then
          local n = room:getSettings("lord_extra_extrasheild") or 0
          p.shield = p.shield + n
        end
  
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "deputyGeneral")
        room:broadcastProperty(p, "kingdom")
        room:broadcastProperty(p, "maxHp")
        room:broadcastProperty(p, "hp")
        room:broadcastProperty(p, "shield")
      end
    end


  -- function role_logic:prepareDrawPile()
  --   local room = self.room
  --   local allCardIds = Fk:getAllCardIds()
  --   local filterCardIds = {}
  --   --卡牌白名单
  --   local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token","th_jie_fuzhi1_cards","th_jie_fuzhi2_cards","th_jie_fuzhi3_cards"}
  --   for i = #allCardIds, 1, -1 do
  --     local id = allCardIds[i]
  --     local card = Fk:getCardById(id)
  --     if card then
  --       if card.is_derived or not table.contains(white_cards, card.package.name) then
  --         table.removeOne(allCardIds, id)
  --         table.insert(room.void, id)
  --         room:setCardArea(id, Card.Void, nil)
  --       end
  --       if table.contains(white_cards, card.package.name) then
  --         if not card.is_derived then
  --           table.insert(filterCardIds, id)
  --         end
  --       end
  --     end
  --   end
  --   local seed = math.random(2 << 32 - 1)
  --   table.shuffle(filterCardIds, seed)
  --   room.draw_pile = filterCardIds
  --   for _, id in ipairs(room.draw_pile) do
  --     room:setCardArea(id, Card.DrawPile, nil)
  --   end
  --   room:doBroadcastNotify("PrepareDrawPile", seed)
  -- end



  return role_logic
end

local role_mode = fk.CreateGameMode{
  name = "ling__role_mode",
  minPlayer = 2,
  maxPlayer = 10,
  logic = role_getlogic,
  rule = "#ling__role_rule&",
  main_mode = "role_mode",
  is_counted = function(self, room)
    return #room.players >= 5
  end,
  -- build_draw_pile = function(self)
  --   local allCardIds = Fk:getAllCardIds()
  --   local filterCardIds = {}
  --   local void = {}
  --   --卡牌白名单
  --   local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
  --   for i = #allCardIds, 1, -1 do
  --     local id = allCardIds[i]
  --     local card = Fk:getCardById(id)
  --     if card then
  --       if card.is_derived or not table.contains(white_cards, card.package.name) then
  --         table.removeOne(allCardIds, id)
  --         table.insert(void, id)
  --       end
  --       if table.contains(white_cards, card.package.name) then
  --         if not card.is_derived then
  --           table.insert(filterCardIds, id)
  --         end
  --       end
  --     end
  --   end
  --   return filterCardIds, void
  -- end,
  surrender_func = function(self, playedTime)
    return Fk.game_modes["aaa_role_mode"].surrenderFunc(self, playedTime)
  end,
}

Fk:loadTranslationTable{
  ["change_general_num"] = "换将卡数量",

  ["enableFourSymbols"] = "四象标记",
  ["#enableFourSymbols"] = "是否开启四象标记，详见游戏模式内注解",
  ["lord_exrta_maxHandcard"] = "主公额外手牌上限",
  ["renegadeExtraChange"] = "内奸额外换将卡数",
  ["renegadeComeBackToLifeCompensation"] = "内奸复活补偿",
  ["#renegadeComeBackToLifeCompensation"] = "内奸失救时，可以亮出身份牌并将体力恢复至1。",
  
  ["late_position_initialHandcard"] = "后置位额外初始手牌数",
  ["late_position"] = "后置位：八号位及以后",
  ["late_position_extraChange"] = "后置位额外换将卡数量",

  ["late_position_start"] = "后置位座位",
  ["late_position_extrasheild"] = "后置位额外护甲",
  ["lord_extra_extrasheild"] = "主公额外护甲",
}

local W = require "ui_emu.preferences"

role_mode.ui_settings = {
  --四象标记
  W.PreferenceGroup{
    W.SwitchRow{
      _settingsKey = "enableFourSymbols",
      title = "enableFourSymbols",
      subTitle = Fk:translate("#enableFourSymbols", Config.language)
    },
    --主公额外手牌上限
    W.SpinRow{
       from = 0,
       to = 4,
      _settingsKey = "lord_extra_maxHancard",
      title = "lord_exrta_maxHandcard"
    },
    --主公额外护甲
    W.SpinRow{
      from = 0,
      to = 5,
      _settingsKey = "lord_extra_extrasheild",
      title = "lord_extra_extrasheild"
    },
    --内奸复活补偿
    W.SwitchRow{
      _settingsKey = "renegadeComeBackToLife",
      title = "renegadeComeBackToLifeCompensation",
      subTitle = Fk:translate("#renegadeComeBackToLifeCompensation", Config.language)
    }
  },
  --后置位
  W.PreferenceGroup{
    --后置位开始座位
    W.SpinRow{
      from = 5,
      to = 99,
      _settingsKey = "late_position_start",
      title = "late_position_start",
    },
    --后置位额外初始手牌数
    W.SpinRow{
      from = 0,
      to = 4,
      _settingsKey = "late_position_initialHandcard",
      title = "late_position_initialHandcard",
    },
    --后置位额外换将卡数量
    --后置位护甲
    W.SpinRow{
      from = 0,
      to = 5,
      _settingsKey = "late_position_extrasheild",
      title = "late_position_extrasheild",
    }

  }
}

Fk:loadTranslationTable{
  ["time limitation: 2 min"] = "游戏时长达到2分钟",
  ["#hx_role-generalnum"] = "请选择可多选的武将数，将取所有非人机玩家选项的平均值（向下取整）",
  ["#ling__choose_role"] = "你可以自选自己的身份，点取消则为随机",
  ["#ling__choose_seat"] = "你可以自选自己的座位，点取消则为随机",
  ["ling__role_mode"] = "多人身份",

  [":ling__role_mode"] = [========================================[
## 多人身份模式简介

至多10人的身份模式，同时加入了换将卡。身份分配参考下表：


| 玩家人数 | 主公 | 忠臣 | 反贼 | 内奸 |
| -------- | ---- | ---- | ---- | ---- |
| 2        | 1    | 0    | 1    | 0    |
| 3        | 1    | 0    | 1    | 1    |
| 4        | 1    | 1    | 1    | 1    |
| 5        | 1    | 1    | 2    | 1    |
| 6        | 1    | 1    | 3    | 1    |
| 7        | 1    | 2    | 3    | 1    |
| 8        | 1    | 2    | 4    | 1    |
| 9        | 1    | 3    | 4    | 1    |
| 10        | 1    | 3    | 4    | 2    |


### 另外，如果仅有一名真人，则可以自选身份和座位。

### 四象标记

#### ☆ 所有选手亮将结束后，主公须在四张四象牌中抽取一张获得，并获得对应四象技能。
#### ☆ 发动四象技能后失去四象牌。一名角色的回合结束后，若反贼全部阵亡，亦失去四象牌。

##### 朱雀
出牌阶段，你可以弃置一张非基本牌，对一名角色造成1点伤害。以此法杀死反贼不执行奖惩。

##### 玄武
你可以将一张牌当【桃】使用。

##### 青龙
回合开始时，你可以弃置两张牌，弃置你判定区里的一张【乐不思蜀】或【兵粮寸断】。

##### 白虎
你可以将一张牌当【杀】或【闪】使用或打出。

  ]========================================],
}



return role_mode
